package com.yunshu.yunshuapp.user;

import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.style.ForegroundColorSpan;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.fasterxml.jackson.databind.JsonNode;
import com.yunshu.yunshuapp.NavigationBar;
import com.yunshu.yunshuapp.R;
import com.yunshu.yunshuapp.WebviewActivity;
import com.yunshu.yunshuapp.network.YSCallback;
import com.yunshu.yunshuapp.network.YSRequest;
import com.yunshu.yunshuapp.utils.YSUtils;

import java.util.Timer;
import java.util.TimerTask;


public class ForgetPWDActivity extends AppCompatActivity implements View.OnClickListener {

    private String mobile;
    private String verfycode;
    private EditText regMobileET;
    private EditText codeET;
    private EditText registerPwdET;
    private Button sendCodeBtn;
    private Timer timer;
    private int seconds;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_forgetpwd);

        NavigationBar bar2 = (NavigationBar) findViewById(R.id.navigationBar);
        bar2.putInActivity(this);
        bar2.setTitle("找回密码");

        regMobileET = (EditText) findViewById(R.id.mobileET1);
        codeET = (EditText) findViewById(R.id.verifycodeET);
        sendCodeBtn = (Button)findViewById(R.id.sendcode);
        registerPwdET = (EditText) findViewById(R.id.registerPwdET);
        this.addListener();
    }

    private void addListener() {
        Button sendCodeBtn = (Button) findViewById(R.id.sendcode);
        sendCodeBtn.setOnClickListener(this);

        Button regBtn = (Button) findViewById(R.id.registerBTN);
        regBtn.setOnClickListener(this);

    }

    @Override
    public void onClick(View view) {

        if (view.getId() == R.id.loginagreement){
            Intent intent = new Intent();
            intent.setClass(this,WebviewActivity.class);
            Bundle bundle = new Bundle();
            bundle.putString("url",YSRequest.BASE_URL + YSRequest.AGREEMENT);
            intent.putExtras(bundle);
            startActivityForResult(intent,0);
        }else if (view.getId() == R.id.sendcode){
            String mobile1 = regMobileET.getText().toString();
            if (!YSUtils.isPhoneNumberValiad(mobile1)){
                this.alert("请输入正确的手机号");
                return;
            }
            mobile = mobile1;
            this.sendVerifyCode(mobile);
        }else if(view.getId() == R.id.registerLink){
            View view1 = findViewById(R.id.register);
            view1.setVisibility(View.VISIBLE);

            View view2 = findViewById(R.id.login);
            view2.setVisibility(View.INVISIBLE);

            NavigationBar bar = (NavigationBar) findViewById(R.id.navigationBarReg);
            bar.putInActivity(this);
            bar.setTitle("注册");
            
        }else if(view.getId() == R.id.registerBTN){
            String mobile1 = regMobileET.getText().toString();
            if (!YSUtils.isPhoneNumberValiad(mobile1)){
                this.alert("请输入正确的手机号");
                return;
            }
            mobile = mobile1;
            String code = codeET.getText().toString();
            if (code == null || code.length() <= 0){
                this.alert("请输入正确的验证码");
                return;
            }
            String pwd = registerPwdET.getText().toString();
            if (pwd == null || pwd.length() < 8 || pwd.length()>20){
                this.alert("密码必须为8～20位，可以包含字母数字");
                return;
            }
            this.register(code,pwd);
        }
    }

    private void register(String code, String pwd) {

        String params = "phone="+mobile+"&code="+code +"&password="+pwd + "&username="+mobile;
        new YSRequest(this).GET(YSRequest.FORGET_PASSWORD, params, new YSCallback() {
            @Override
            public void onResponse(int isSuccess, JsonNode resObj) {
                if (isSuccess == YSRequest.REQUEST_OK) {
                    runOnUiThread(new Runnable() {      // UI thread
                        @Override
                        public void run() {
                            new AlertDialog.Builder(ForgetPWDActivity.this).setTitle("提示")//设置对话框标题
                                    .setPositiveButton("我知道了", new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialogInterface, int i) {
                                            ForgetPWDActivity.this.finish();                                        }
                                    })
                                    .setMessage("恭喜你，修改密码成功！").show();
                        }
                    });
                }

            }
        });
    }


    private void sendVerifyCode(String mobile) {
        sendCodeBtn.setEnabled(false);
        new YSRequest(this).GET(YSRequest.SEND_CODE, "phone=" + mobile, new YSCallback() {
            @Override
            public void onResponse(int isSuccess, JsonNode result) {
                if (isSuccess == YSRequest.REQUEST_OK){
                    showToast("验证码发送成功");
                    seconds = 60;
                    if (timer != null ) timer.cancel();
                    timer = new Timer();
                    timer.schedule(task, 1000, 1000);       // timeTask
                }else{
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            sendCodeBtn.setEnabled(true);
                        }
                    });
                }
            }
        });



    }

    private void alert(final String s) {
        runOnUiThread(new Runnable() {      // UI thread
            @Override
            public void run() {
                new AlertDialog.Builder(ForgetPWDActivity.this).setTitle("提示")//设置对话框标题
                        .setPositiveButton("我知道了", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {

                            }
                        })
                        .setMessage(s).show();
            }
        });

    }

    private void showToast(final String s) {

        runOnUiThread(new Runnable() {      // UI thread
            @Override
            public void run() {
                Toast.makeText(getApplicationContext(), s,
                        Toast.LENGTH_SHORT).show();
            }
        });

    }

    TimerTask task = new TimerTask() {
        @Override
        public void run() {

            runOnUiThread(new Runnable() {      // UI thread
                @Override
                public void run() {
                    seconds--;
                    sendCodeBtn.setText(seconds+"s");
                    if(seconds < 0){
                        timer.cancel();
                        sendCodeBtn.setText("重新发送验证码");
                        sendCodeBtn.setEnabled(true);
                    }
                }
            });
        }
    };
}
